#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int getLog(int N) {
	int log = 0;
    int lN = 1;
    while (lN <= N) {
        lN <<= 1;
        ++log;
    }
	return --log;
}

void LCA(vector< vector<int> >& P, vector<int>& T, int N, int log) {
    for (int i = 0; i < N; ++i) 
        P[i][0] = T[i];
   
    for (int i = 0; i < N; ++i)
        for (int j = 1; j < log; ++j)
            P[i][j] = (P[i][j - 1] != -1) ? P[P[i][j - 1]][j - 1] : -1;
}

int getAnswer(vector< vector<int> >& P, vector<int>& T, vector<int>& L, int i, int j) {
    if (L[i] < L[j])
        swap(i, j);
    int log = getLog(L[i]) -1;
    for (int l = log; l >= 0; --l)
        if (L[i] - (1 << l) >= L[j])
            i = P[i][l];
    if (i == j)
        return i;
    for (int k = log; k >= 0; --k)
        if (P[i][k] != -1 && P[j][k] != -1 && P[i][k] != P[j][k]) {
              i = P[i][k];
              j = P[j][k];
        }
    return T[i];
}

int main() {    
    ifstream ifile("in.txt");
    int N;
    ifile >> N;
    int log = getLog(++N);

    vector<int> T(N); // parents
    T[0] = -1;
    vector<int> L(N, 0); //level number
    vector< vector <int> > P(N); //(2^j)th parent
    for (int i = 0; i < N; ++i)
        P[i].resize(log, -1);

    for(int i = 1; i < N; ++i) {
        int id, p;
        ifile >> id >> p;
        T[id] = p;
        L[id] = L[p] + 1;
    }

    LCA(P, T, N, log);

    int M, i, j;
    ifile >> M;
    for (int l = 0; l < M; ++l)
    {
        ifile >> i >> j;
        cout << getAnswer(P, T, L, i, j) << endl;
    }
    ifile.close();
    return 0;
}